package org.example.router.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.client.ServiceBClient;
import org.example.dao.RouterparametersDao;
import org.example.po.Routerparameters;
import org.example.router.IRouter;
import org.example.utils.CodeCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @author jz
 * @version 1.0
 * @description TODO
 * @date 2024/10/14 21:47
 */
public abstract class RouterAbstract implements IRouter {
    public static final Logger LOGGER = LoggerFactory.getLogger(RouterAbstract.class);

    @Resource
    private RouterparametersDao routerparametersDao;

    @Resource
    @Lazy
    protected ServiceBClient serviceBClient;

    @Override
    public boolean router(Map<String, String> map, HttpServletResponse response) {
        // TODO 获取参数，校验

        try {
            return execute(map, response);
        } catch (Exception e) {
            LOGGER.error(map.get("rulename") + "路由出错" + e);
        }

        return true;
    }

    public abstract boolean execute(Map<String, String> map, HttpServletResponse response) throws Exception;

    /***
     * 获取路由需要的参数
     * @param key
     * @return java.util.List<Routerparameters>
     * @author jz
     * @date 2024/10/14 23:05
    */
    protected List<Routerparameters> searchDatabase(String key){

        List<Routerparameters> list = CodeCache.getRouterparameters(key);
        // 更新数据库时，走数据库
        if (!CodeCache.isUsing){
            QueryWrapper<Routerparameters> queryWrapper = new QueryWrapper<>();
            int i = key.indexOf("_");
            String tradeCode = key.substring(0,i);
            String projectName = key.substring(i+1);
            queryWrapper.eq("rulename",tradeCode);
            queryWrapper.eq("projectName",projectName);
            list = routerparametersDao.selectList(queryWrapper);
        }
        return list;
    }

}
